package com.ht.WeNas.config.web;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.resource.NoResourceException;
import com.ht.WeNas.data.vo.Res;
import com.ht.WeNas.utils.exceptions.MessageException;
import com.ht.WeNas.utils.exceptions.UserNotLoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.net.SocketTimeoutException;
import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionAdvice {
    @ExceptionHandler(MessageException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Res<Void> handleMessageException(MessageException e) {
        return Res.fail(e.getMessage());
    }

    @ExceptionHandler(IORuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Res<Void> handleIoRuntimeException(IORuntimeException e) {
        log.warn("IO错误", e);
        return Res.fail("拒绝访问");
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Res<Void> handleHttpMessageNotReadableException (HttpMessageNotReadableException e) {
        log.warn("传入参数错误", e);
        return Res.fail("传入参数错误，请检查输入参数");
    }

    @ExceptionHandler(MultipartException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Res<Void> handleMultipartException(MultipartException e) {
        if (e.getMessage().startsWith("Maximum upload size exceeded")) {
            return Res.fail("上传文件过大，请更换文件重试");
        }
        log.warn("MultipartFile 错误", e);
        return Res.fail("上传方式错误，请重试");
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Res<Void> handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e) {
        log.error("数据库错误", e);
        return Res.fail("系统错误，请稍后重试");
    }

    @ExceptionHandler(NumberFormatException.class)
    public Res<Void> handeNumberFormatException(NumberFormatException e) {
        log.error("数字转换错误", e);
        return Res.fail("数据校验错误，请检查输入");
    }

    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Res<Void> handleNullPointerException(NullPointerException e) {
        log.warn("参数错误", e);
        return Res.fail("参数错误");
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Res<Void> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return Res.fail("系统错误，请稍后重试");
    }

    /**
     * JSR303 校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Res<Void> handle(MethodArgumentNotValidException e){
        StringBuilder message = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(err -> {
            message.append(err.getDefaultMessage()).append(".");
        });
        return Res.fail(message.toString());
    }

    /**
     * 数据校验异常
     */
    @ExceptionHandler({IllegalArgumentException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Res<Void> handleDataIntegrityViolationException(Exception e) {
        String message = e.getMessage();
        if (message.contains("Duplicate entry")) {
            return Res.fail("数据重复，请检查后重试");
        }
        log.warn(message, e);
        return Res.fail("数据异常，请检查后重试");
    }

    @ExceptionHandler({NoResourceFoundException.class, NoResourceException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Res<Void> handleNoResourceException(Exception ignore) {
        return Res.fail("资源为空");
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Res<Void> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.warn(e.getMessage());
        return Res.fail("请求参数错误");
    }
    
    @ExceptionHandler(UserNotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Res<Void> handleUserNotLogin() {
        log.error("触发UserNotLoginException");
        return Res.fail("用户未登录");
    }
    
    @ExceptionHandler(SocketTimeoutException.class)
    public void handleSocketTimeoutException(SocketTimeoutException ignore) {
    }
}
